<script setup lang="ts">
import { DataProp } from '@/types/selfdefine/Layout'
import { getRandomCount, getRandomAnimation } from '@/utils/tools/tools'
import { ref, onMounted, nextTick, watch, onBeforeUnmount, computed } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
import { useLangStore } from '@/stores/langStore'
import { storeToRefs } from 'pinia'
const { tipsButton } = storeToRefs(useLangStore())

const props = defineProps<{
  data: DataProp | undefined
}>()

// ✅ 2. 使用 computed 生成 blogPosts（核心）
const blogPosts = computed(() => {
  destroySlick()
  //  console.log("Blog 内容更新并销毁slick");
  const list = props.data?.partContentVoList || []
  return list.map((item) => ({
    id: item.partId,
    title: item.title,
    image: item.imageUrl,
    summary: item.content,
    comments: getRandomCount(),
    likes: getRandomCount(),
    routeName: item.url,
    delay: '0.4s',
  }))
})

// ✅ 3. Slick 初始化（只一次）
let slickInited = false
const initSlick = () => {
  if (!slickInited) {
    window.$('.blog-slider').slick({
      infinite: true,
      slidesToShow: 3,
      slidesToScroll: 1,
      arrows: true,
      dots: false,
      autoplay: true,
      autoplaySpeed: 7000,
      speed: 500,
      cssEase: 'linear',
    })
    slickInited = true
  }
}

const destroySlick = () => {
  if (slickInited) {
    window.$('.blog-slider').slick('unslick')
    slickInited = false
  }
}
onMounted(async () => {
  await nextTick()

  // 🔹 确保 DOM 渲染完成，且有数据
  if (slickInited) return
  if (!window.$ || $('.blog-slider').length === 0) return

  try {
    initSlick()
    slickInited = true
    // console.log('✅ Slick initialized')
  } catch (e) {
    console.warn('Slick init failed:', e)
  }
})

watch(
  blogPosts, // 👈 直接监听 computed 引用
  (newPosts, oldPosts) => {
    if (!newPosts.length) return

    // console.log('🔄 检测到 blogPosts 变化，重新初始化 Slick')

    // 🔁 销毁旧实例
    if (slickInited) {
      window.$('.blog-slider').slick('unslick')
      slickInited = false
    }

    // ✅ 等待 DOM 更新完成
    nextTick(() => {
      try {
        initSlick()
        slickInited = true
        // console.log('✅ Slick 重新初始化成功')
      } catch (e) {
        console.warn('Slick re-init failed:', e)
      }
    })
  },
  { immediate: true } // 👈 组件挂载时也触发一次
)
const goToBlogDetail = (route?: string) => {
  if (route) router.push(route)
}
</script>
<template>
  <section class="section-padding our_articles" id="blog">
    <div class="container" v-if="data.partTitle">
      <!-- Section Header -->
      <div class="section-header text-center">
        <div class="section-heading">
          <h3 class="text-custom-black">
            {{ data.partTitle.slice(0, 3) }}
            <span class="text-custom-blue">{{ data.partTitle.slice(3) }}</span>
          </h3>
          <div class="section-description">
            <p class="text-light-dark">
              {{ data.content }}
            </p>
          </div>
        </div>
      </div>

      <!-- Blog Slider -->
      <div class="row">
        <div class="col-12">
          <div class="blog-slider arrow-layout-2 row">
            <article
              v-for="post in blogPosts"
              :key="post.id"
              :class="`col-12 post slide-item wow ${getRandomAnimation()}`"
              :data-wow-delay="post.delay"
            >
              <div class="post-wrapper bx-wrapper">
                <div class="post-img animate-img">
                  <a href="#" @click.prevent="goToBlogDetail(post.routeName)">
                    <img :src="post.image" alt="img" class="full-width" />
                  </a>
                </div>
                <div class="blog-meta padding-20 bg-custom-white p-relative">
                  <h2>
                    <a href="#" class="text-custom-black fw-600 fs-20">{{
                      post.title
                    }}</a>
                  </h2>
                  <div class="post-meta mb-xl-20">
                    <a href="#" class="text-light-dark mr-1">
                      <span class="text-custom-blue"
                        ><i class="fas fa-comment"></i
                      ></span>
                      {{ post.comments }} Comments
                    </a>
                    <a href="#" class="text-light-dark mr-1">
                      <span class="text-custom-blue"
                        ><i class="fas fa-thumbs-up"></i
                      ></span>
                      {{ post.likes }} Likes
                    </a>
                  </div>
                  <div class="post-heading">
                    <p class="text-light-dark no-margin">{{ post.summary }}</p>
                  </div>
                </div>
                <div class="post-footer">
                  <a
                    href="#"
                    class="fs-14 fs-600"
                    @click.prevent="goToBlogDetail(post.routeName)"
                    >{{ tipsButton }}</a
                  >
                </div>
              </div>
            </article>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>
